package org.dreamwork.assistant.tools.persistence.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Enumeration;

/**
 * Created by seth.yang on 2016/7/26
 */
public class SwingTool {
    public static void center (JFrame frame) {
        Dimension d = frame.getSize ();
        Dimension D = Toolkit.getDefaultToolkit ().getScreenSize ();
        int x = (D.width - d.width) / 2, y = (D.height - d.height) / 2;
        if (x < 0) x = 0;
        if (y < 0) y = 0;
        frame.setLocation (x, y);
    }

    public static void center (JDialog dialog, JFrame frame) {
        Dimension d = dialog.getSize ();
        Dimension D = frame.getSize ();
        Point P = frame.getLocation ();
        int x = P.x + (D.width - d.width) / 2, y = P.y + (D.height - d.height) / 2;
        System.out.println ("x = " + x + ", y = " + y);
        if (x < 0) x = 0;
        if (y < 0) y = 0;
        dialog.setLocation (x, y);
    }

    public static void setFont (Font font) {
        UIDefaults uid = UIManager.getDefaults ();

        Enumeration<Object> e = uid.keys ();
        for (; e.hasMoreElements (); ) {
            Object o = e.nextElement ();
            if (o != null && o.toString ().contains (".font")) {
                uid.put (o, font);
            }
        }
    }

    public static void addConfirmExit (final JFrame frame) {
        frame.addWindowListener (new WindowAdapter () {
            @Override
            public void windowClosing (WindowEvent e) {
                confirmExit (frame);
            }
        });
    }

    public static void confirmExit (JFrame frame) {
        int option = JOptionPane.showConfirmDialog (frame, "Are you sure to exit ?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (option == JOptionPane.NO_OPTION) {
            frame.setDefaultCloseOperation (WindowConstants.DO_NOTHING_ON_CLOSE);
        } else {
            System.exit (0);
        }
    }
}
